from flask import Blueprint, jsonify, request
from app.services.recipe_service import RecipeService, adjust_calories, adjust_macronutrients, adjust_calories2, adjust_macronutrients2


bp = Blueprint('recipe_routes', __name__)

# 初始化服务
recipe_service = RecipeService()

# 获取指定日期的食谱，如果没有记录则创建
@bp.route('/<user_id>/<date>', methods=['GET', 'POST'])
def get_recipe(user_id, date):
    try:
        # 调用服务层方法获取食谱或模板
        recipe_or_template = recipe_service.get_recipes_by_date(user_id, date)
        # print(recipe_or_template)
        return jsonify({
            "message": "",
            "recipe": recipe_or_template
        }), 200

    except Exception as e:
        return jsonify({"message": str(e)}), 500



@bp.route('/nsga', methods=['GET'])
def get_nsga():
    try:
        total_calories = float(request.args.get('total_calories', 2000))
        macro_ratio = {
                "carbohydrate": float(request.args.get('carbohydrate_ratio', 0.5)),
                "protein": float(request.args.get('protein_ratio', 0.3)),
                "fat": float(request.args.get('fat_ratio', 0.2)),
            }
        # 获取请求中的用户配置项（使用查询参数）
        config = {
            "total_calories": total_calories,  # 默认2000 kcal
            "meal_count": int(request.args.get('meal_count', 4)),  # 默认4餐
            "macro_ratio": macro_ratio,
            "meal_food_types": int(request.args.get('meal_food_types', 3)),  # 默认5种食物
            "local": request.args.get('local', '私家'),  # 默认
            "food_type": request.args.get('food_type', '食材') , # 默认食材
            "user_id": request.args.get('user_id'),
            "date": request.args.get('date')
        }

        # 使用 RecipeService 来生成食谱
        best_recipe = recipe_service.generate_diet_plan(config)
        best_recipe = adjust_macronutrients2(best_recipe, macro_ratio['carbohydrate'], macro_ratio['fat'], macro_ratio['protein'])
        best_recipe = adjust_calories2(best_recipe, target_calories=total_calories)


        # 返回生成的食谱
        return jsonify(best_recipe), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 400




@bp.route('/nsga/daily', methods=['GET'])
def get_nsga_daily():
    """处理用户请求，生成食谱"""
    try:
        target_calc = float(request.args.get('total_calories', 2000))
        macro_ratio = {
                "carbohydrate": float(request.args.get('carbohydrate_ratio', 0.5)),
                "protein": float(request.args.get('protein_ratio', 0.3)),
                "fat": float(request.args.get('fat_ratio', 0.2)),
            }
        # 获取请求中的用户配置项（使用查询参数）
        config = {
            "total_calories": target_calc,  # 默认2000 kcal
            "meal_count": int(request.args.get('meal_count', 4)),  # 默认4餐
            "macro_ratio": macro_ratio,
            "meal_food_types": int(request.args.get('meal_food_types', 5)),  # 默认5种食物
            "local": request.args.get('local', '四川'),  # 默认四川
            "food_type": request.args.get('food_type', '食材')  # 默认食材
        }

        # 使用 RecipeService 来生成食谱
        best_recipe = recipe_service.generate_diet_plan2(config)

        # Debugging: 打印生成的 best_recipe 数据结构
        print("Best Recipe:", best_recipe)

        # 获取 recipe_data（即食谱中的每餐信息）
        recipe_data = best_recipe.get('recipe_data', [])

        # 初始化返回的总热量和营养素数据
        total_day_calories = 0
        total_day_carbs = 0
        total_day_protein = 0
        total_day_fat = 0

        # 格式化食谱并计算一天的总数据
        formatted_recipe = []
        for meal in recipe_data:
            # 确保 meal 是一个字典且包含 'food_details'
            if isinstance(meal, dict) and 'food_details' in meal:
                meal_data = {
                    'meal_calories': 0,
                    'meal_carbs': 0,
                    'meal_protein': 0,
                    'meal_fat': 0,
                    'food_details': []
                }

                for food in meal['food_details']:
                    meal_data['meal_calories'] += food['calories']
                    meal_data['meal_carbs'] += food['carbohydrate']
                    meal_data['meal_protein'] += food['protein']
                    meal_data['meal_fat'] += food['fat']
                    meal_data['food_details'].append(food)

                # 计算每餐的营养素配比
                meal_data['carbohydrate_ratio'] = meal_data['meal_carbs']*4 / meal_data['meal_calories'] if meal_data[
                                                                                                              'meal_calories'] > 0 else 0
                meal_data['protein_ratio'] = meal_data['meal_protein']*4 / meal_data['meal_calories'] if meal_data[
                                                                                                           'meal_calories'] > 0 else 0
                meal_data['fat_ratio'] = meal_data['meal_fat']*9 / meal_data['meal_calories'] if meal_data[
                                                                                                   'meal_calories'] > 0 else 0

                # 累加一天的总热量和营养素
                total_day_calories += meal_data['meal_calories']
                total_day_carbs += meal_data['meal_carbs']
                total_day_protein += meal_data['meal_protein']
                total_day_fat += meal_data['meal_fat']

                formatted_recipe.append(meal_data)
            else:
                raise ValueError(
                    "Unexpected data format in 'recipe_data'. Each meal must be a dictionary containing 'food_details'.")

        # 计算一天的总营养素配比
        day_carbohydrate_ratio = total_day_carbs*4 / total_day_calories if total_day_calories > 0 else 0
        day_protein_ratio = total_day_protein*4 / total_day_calories if total_day_calories > 0 else 0
        day_fat_ratio = total_day_fat*9 / total_day_calories if total_day_calories > 0 else 0

        # 创建返回的总信息（总的食谱信息部分）
        daily_recipe = {
            'total_day_calories': total_day_calories,
            'total_day_carbs': total_day_carbs,
            'total_day_protein': total_day_protein,
            'total_day_fat': total_day_fat,
            'carbohydrate_ratio': day_carbohydrate_ratio,
            'protein_ratio': day_protein_ratio,
            'fat_ratio': day_fat_ratio
        }


        recipe_dict = {
            'daily_recipe': daily_recipe,
            'recipe_data': formatted_recipe
        }
        
        recipe_dict = adjust_macronutrients(recipe_dict, macro_ratio['carbohydrate'], macro_ratio['fat'], macro_ratio['protein'])
        recipe_dict = adjust_calories(recipe_dict, target_calc)

        # 返回的结构：总信息 + 每餐的详细信息
        return jsonify({
            'daily_recipe': daily_recipe,
            'recipe_data': formatted_recipe
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400




# 获取所有食谱
@bp.route('/', methods=['GET'])
def get_all_recipes():
    recipes = recipe_service.get_all_recipes()
    return jsonify([{
        'recipe_id': recipe.recipe_id,
        'name': recipe.name,
        'description': recipe.description
    } for recipe in recipes]), 200

# 获取单个食谱
@bp.route('/<int:recipe_id>', methods=['GET'])
def get_recipe_by_id(recipe_id):
    recipe = recipe_service.get_recipe_by_id(recipe_id)
    if not recipe:
        return jsonify({'error': 'Recipe not found'}), 404
    return jsonify({
        'recipe_id': recipe.recipe_id,
        'name': recipe.name,
        'description': recipe.description
    }), 200

# 创建新食谱
@bp.route('/', methods=['POST'])
def create_recipe():
    data = request.get_json()
    if 'name' not in data or 'description' not in data:
        return jsonify({'error': 'Name and description are required'}), 400
    new_recipe = recipe_service.create_recipe(data)
    return jsonify({
        'recipe_id': new_recipe.recipe_id,
        'name': new_recipe.name,
        'description': new_recipe.description
    }), 201

# 更新食谱
@bp.route('/<int:recipe_id>', methods=['PUT'])
def update_recipe(recipe_id):
    data = request.get_json()
    updated_recipe = recipe_service.update_recipe(recipe_id, data)
    if not updated_recipe:
        return jsonify({'error': 'Recipe not found'}), 404
    return jsonify({
        'recipe_id': updated_recipe.recipe_id,
        'name': updated_recipe.name,
        'description': updated_recipe.description
    }), 200

# 删除食谱
@bp.route('/<int:recipe_id>', methods=['DELETE'])
def delete_recipe(recipe_id):
    deleted_recipe = recipe_service.delete_recipe(recipe_id)
    if not deleted_recipe:
        return jsonify({'error': 'Recipe not found'}), 404
    return jsonify({'message': 'Recipe deleted successfully'}), 200